package com.foreveross.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import net.sf.json.JSONObject;

import com.foreveross.crawl.dto.TaskModelDto;
import com.foreveross.crawl.vo.MetadataStructure;
import com.foreveross.crawl.vo.TaskModelBeta1;
import com.foreveross.taskservice.common.bean.TaskModel;
import com.foreveross.taskservice.common.model.AbstractChannelModel;
import com.foreveross.taskservice.common.model.airfreight.AirFreightChannelModel;

/**
 * 拼装JSON信息
 * @author luofangyi
 *
 */
public class SpliteJson {

	
	/**
	 * 拼装元数据定义的列头JSON信息
	 * @param dto
	 * @return
	 */
	public static Map<String, String> packagingColumsForMatadata(TaskModelDto dto){
		
		Map<String, String> metaMap = getMetadataDesc(dto);
		/*if(metaMap == null){
			return null;
		}
		
		StringBuilder sb = new StringBuilder("");
		Set<String> keySet = metaMap.keySet();
		sb.append("[{");
		for(String key : keySet){
			sb.append(getJsonStr(key, metaMap.get(key)));
		}
		if((sb.lastIndexOf(",") == sb.length() - 1)){//最后一个字符是否为","
			sb.deleteCharAt(sb.length() - 1);
		}
		sb.append("}]");
		
		return sb.toString();*/
		return metaMap;
	}

	private static StringBuffer getJsonStr(String key, String value) {
		StringBuffer sb = new StringBuffer("");
		sb./*append("\"").*/append(key)/*.append("\"")*/
			.append(":").
			/*append("\"").*/append(value)/*.append("\"")*/.append(",");
		return sb;
	}
	
	private static Map<String, String> getMetadataDesc(TaskModelDto dto){
		
		//TODO 去掉注释
//		if(dto.getMetadata() == null){
//			return null;
//		}
		Map<String, String> metaMap = new HashMap<String, String>();
		List<MetadataStructure> metadataList = new ArrayList<MetadataStructure>();
		metadataList.add(new MetadataStructure("fromCityName", "出发城市"));
		metadataList.add(new MetadataStructure("toCityName", "到达城市"));
		metadataList.add(new MetadataStructure("createTime", "任务创建时间"));
//		List<MetadataStructure> metadataList = dto.getMetadata();
		
		for(MetadataStructure metadata : metadataList){
			metaMap.put(metadata.getNameEN(), metadata.getNameCN());
		}
		return metaMap;
	}
	
	private static String spliteBody(TaskModelDto dto){
		
		StringBuilder sb = new StringBuilder("");
		//将最后面的"}"符号换成","  用于拼装后面的json串
//		sb.append(JSONObject.toJSON(dto).toString().replaceAll("}", ","));
		JSONObject jsonObject = JSONObject.fromObject("");
//		jsonObject.g
		Map<String, String> bodyMap = new HashMap<String, String>();
		List<String> explodeList = explodeString(dto);
		for(int i = 0; i < explodeList.size() - 1; i++){
			bodyMap.put(explodeList.get(i), explodeList.get(i + 1));
			i++;
		}
		Map<String, String> columMap = getMetadataDesc(dto);
		if(columMap == null){
			return null;
		}
		Set<String> columSet = columMap.keySet();
		Set<String> bodySet = bodyMap.keySet();
		Iterator<String> iterBody = bodySet.iterator();
		while(iterBody.hasNext()){
			String key = iterBody.next();
			if(columSet.contains(key)){
				sb.append(getJsonStr(key, bodyMap.get(key)));
			}
		}
		if((sb.lastIndexOf(",") == sb.length() - 1)){//最后一个字符是否为","
			sb.deleteCharAt(sb.length() - 1);
		}
		sb.append("}");
		return sb.toString();
	}
	
	/**
	 * 拼装单个TaskModelDto对象json串
	 * @return
	 */
	public static String packagingSingle(TaskModelDto dto){
		StringBuffer sb = new StringBuffer("[");
		sb.append(spliteBody(dto));
		sb.append("]");
		return sb.toString();
	}
	
	/**
	 * 拼装List<TaskModelDto>对象json串
	 * @param dtoList
	 * @return
	 */
	public static String packagingList(List<TaskModelDto> dtoList){
		StringBuffer sb = new StringBuffer("[");
		for(TaskModelDto dto : dtoList){
			sb.append(spliteBody(dto)).append(",");
		}
		if((sb.lastIndexOf(",") == sb.length() - 1)){//最后一个字符是否为","
			sb.deleteCharAt(sb.length() - 1);
		}
		sb.append("]");
		return sb.toString();
	}

	private static List<String> explodeString(TaskModelDto dto) {
		String paramter = "[{\"createTime\":\"2014-06-20 16:54:19\",\"fromCity\":\"pek\",\"fromCityName\":\"北京\",\"toCity\":\"bkk\",\"toCityName\":\"曼谷\"}]";
//		dto.getPraramterJson();
////		com.alibaba.fastjson.JSONArray array = JSONObject.parseArray(paramter);
//		Iterator<Object> iter = array.iterator();
		List<String> explode = new ArrayList<String>();
//		while(iter.hasNext()){
//			String element = iter.next().toString();
//			element = element.replace("{\"", "").replace("\"}", "");
//			String[] groupsFirst = element.split("\",\"");
//			for(String groupFirst : groupsFirst){
//				String[] groupsSecond = groupFirst.split("\":\"");
//				for(String groupSecond : groupsSecond){
//					explode.add(groupSecond);
//				}
//			}
//		}
		return explode;
	}
	
	
	
	public static void main(String[] args){
		
		TaskModel task = new TaskModel();
		task.setAttachHbaseKey("20017");
		task.setCreateTime(new Date());
		task.setFromCity("pek");
		task.setFromCityName("北京");
		task.setToCity("bkk");// 曼谷
		// task.setToCity("cnx");// 清迈
		// task.setToCity("pus");//釜山
		// task.setToCity("aal");//Aalborg 奥尔堡
		// task.setToCity("ath");//雅典
		task.setToCityName("曼谷");
		task.setFlightDate("2014-06-19");
		task.setReturnGrabDate("2014-06-28");
		task.setIsReturn(0);// 0:单程 1:往返
		task.setIsInternational(0);// 国际
		task.setId(UUID.randomUUID().toString());
		AbstractChannelModel channel = new AirFreightChannelModel();
		channel.setId(24L);
		channel.setName("泰航");
		task.setChannel(channel);

//		TaskModelBeta1 beta = TaskModelBeta1.adapterTaskModel(task);
//		TaskModelDto dto = new TaskModelDto(beta.getId(), beta.getChannelId(), beta.getChannelName(), beta.getIsProxyIp(), beta.getPraramterJson(), beta.getMetadata(), beta.getTaskStartDate(), beta.getTaskEndDate(), "", "", "");
//		List<TaskModelDto> list = new ArrayList<TaskModelDto>();
//		list.add(dto);
//		System.out.println(packagingSingle(dto));
//		System.out.println(packagingList(list));
//		System.out.println(JSONObject.toJSON(dto).toString());
//		System.out.println(packagingColumsForMatadata(dto));
	}
	
	
}